<?php

class QWeatherJWT {
    private $privateKey;
    private $credentialId;
    private $projectId;
    private $expSeconds;

    public function __construct($privateKeyBase64, $credentialId, $projectId, $expSeconds = 86400) {
        $this->privateKey = $privateKeyBase64;
        $this->credentialId = $credentialId;
        $this->projectId = $projectId;
        $this->expSeconds = $expSeconds;
    }

    private function base64url_encode($data) {
        return rtrim(strtr(base64_encode(json_encode($data)), '+/', '-_'), '=');
    }

    public function generate() {
        // 解码私钥
        $privateKeyBytes = base64_decode($this->privateKey);
        // 提取32字节的私钥
        $privateKeyRaw = substr($privateKeyBytes, -32);

        // 创建JWT header
        $header = [
            'alg' => 'EdDSA',
            'typ' => 'JWT',
            'kid' => $this->credentialId
        ];

        // 创建JWT payload
        $now = time();
        $payload = [
            'iat' => $now,
            'exp' => $now + $this->expSeconds,
            'aud' => $this->projectId
        ];

        // 编码header和payload
        $headerB64 = $this->base64url_encode($header);
        $payloadB64 = $this->base64url_encode($payload);

        // 创建签名数据
        $signingInput = $headerB64 . '.' . $payloadB64;

        // 使用Ed25519签名
        $signature = sodium_crypto_sign_detached(
            $signingInput,
            $privateKeyRaw
        );

        // 编码签名
        $signatureB64 = rtrim(strtr(base64_encode($signature), '+/', '-_'), '=');

        // 组合JWT
        return $headerB64 . '.' . $payloadB64 . '.' . $signatureB64;
    }
}

// 使用示例
$privateKeyBase64 = "MC4CAQAwBQYDK2VwBCIEIMdF7GgFu0F1PnVlZPqqKivUX1ZCSyM3NYsLkdgVYiPy";
$credentialId = "C9WJGUFUDX";
$projectId = "4F87KPK28B";

$jwt = new QWeatherJWT($privateKeyBase64, $credentialId, $projectId);
$token = $jwt->generate();

echo $token . "\n"; 